#include "WanderState.h"
#include "Random.h"
#include "Search.h"

WanderState::WanderState()
{
	m_SelectNode = true;
	m_PathIndex = 0;
	m_Target = -1;
	m_HasEntered = false;
}

WanderState::~WanderState()
{

}

void WanderState::Update(AiAgent* Agent)
{
	m_Graph = Agent->ReturnGraph();

	if(m_SelectNode)
	{
		int OldTarget = m_Target;
		while(true)
		{
			m_Target = m_Graph->GetNode(RandomInt(0, m_Graph->GetNumNodes())).ReturnId();
			if(m_Target != OldTarget)
			{
				break;
			}
		}
		Search s;
		m_Path = s.BFS(*m_Graph, m_Graph->ReturnIDofClosest(Agent->ReturnPos()), m_Graph->GetNode(m_Target).ReturnId());
		m_SelectNode = false;
	}
	else
	{

		//if we've reached our target
		if(VecLength(Agent->ReturnPos() - m_Graph->GetNode(m_Target).ReturnPos()) <= 0.5)
		{
			if(!m_HasEntered)
			{
				m_HasEntered = true;
			}
		}
		else if(VecLength(Agent->ReturnPos() - m_Graph->GetNode(m_Path[m_PathIndex]).ReturnPos()) <= 0.1f && m_PathIndex < m_Path.size())
		{
			m_PathIndex++;
		}
		Agent->SetVel(Normalised(m_Graph->GetNode(m_Path[m_PathIndex]).ReturnPos() - Agent->ReturnPos()) * 3);

	
		if(m_HasEntered)
		{
			m_SelectNode = true;
			m_HasEntered = false;
		}
	}

}